﻿#include "CheckOptionAttributeSetting.h"
#include <iostream>
#include <QFileInfoList>
#include <qDebug>
#include <QXmlStreamReader>

CheckOptionAttributeSetting::CheckOptionAttributeSetting(const QString& file) {
	readFile = file;
}

void CheckOptionAttributeSetting::getXml(QXmlStreamReader& readerStream
	, QSharedPointer<QVector<QString>>& xmlCout
	, const QString& nodeName) {
	readerStream.readNext( );
	// 获取输出选项
	while( !( readerStream.name( ) == nodeName && readerStream.isEndElement( ) ) ) {
		if( !readerStream.isEndElement( ) ) {
			QStringRef name = readerStream.name( );
			if( !name.isEmpty( ) ) {
				QString string = name.toString( );
				xmlCout.data( )->append(string);
			}
		}
		readerStream.readNext( );
	}
}

QSharedPointer<QHash<QString, QSharedPointer<QVector<QString>>>> CheckOptionAttributeSetting::readDefaultFile( ) {
	QSharedPointer<QHash<QString, QSharedPointer<QVector<QString>>>> result(new QHash<QString, QSharedPointer<QVector<QString>>>);
	QFileInfo info(readFile);
	if( !info.exists( ) ) {
		QFile filerRead(":/xml/defaultSettings.xml");
		filerRead.open(QIODevice::ReadOnly | QIODevice::Text);
		QByteArray byteArray = filerRead.readAll( );
		filerRead.close( );
		filerRead.setFileName(readFile);
		if( !filerRead.open(QIODevice::WriteOnly | QIODevice::Text) ) {
			std::cout << QString("文件写入失败，请联系服务\t").toLocal8Bit( ).constData( ) << std::endl;
			return result;
		}
		filerRead.write(byteArray);
		filerRead.close( );
	}
	QFile filerRead(readFile);
	if( !filerRead.open(QIODevice::ReadOnly | QIODevice::Text) ) {
		std::cout << QString("文件打开失败，请检查\t" + readFile + "\t 是否存在").toLocal8Bit( ).constData( ) << std::endl;
		return result;
	}
	QXmlStreamReader readerStream(&filerRead);
	QSharedPointer<QVector<QString>> xmlCout(new QVector<QString>);
	QSharedPointer<QVector<QString>> xmlIstream(new QVector<QString>);
	QSharedPointer<QVector<QString>> xmlFile(new QVector<QString>);
	while( readerStream.readNext( ) && !readerStream.atEnd( ) ) {
		if( readerStream.isStartElement( ) && readerStream.name( ) == "setting" ) {
			while( readerStream.readNext( ) && !readerStream.isEndElement( ) ) {
				if( readerStream.name( ) == coutNodeName ) {
					getXml(readerStream, xmlCout, coutNodeName);
				} else if( readerStream.name( ) == istreamNodeName ) {
					getXml(readerStream, xmlIstream, istreamNodeName);
				} else if( readerStream.name( ) == fileNodeName ) {
					getXml(readerStream, xmlFile, fileNodeName);
				}
			}
		}
	}
	if( xmlCout->size( ) > 0 )
		result.data( )->insert(coutNodeName, xmlCout);
	if( xmlIstream->size( ) > 0 )
		result.data( )->insert(istreamNodeName, xmlIstream);
	if( xmlFile->size( ) > 0 )
		result.data( )->insert(fileNodeName, xmlFile);
	return result;
}
